<?php
/**
 * 多主键
 *
 * Author: Zeon
 * Date: 2017-12-22
 * Created by Panxsoft.
 */
namespace App\Models\Concerns;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;

/**
 * 多主键需要改写 laravel Model
 *
 * @link https://stackoverflow.com/questions/36332005/laravel-model-with-two-primary-keys-update
 *
 * @mixin Model
 */
trait HasCompositePrimaryKey
{
    /**
     * Set the keys for a save update query.
     *
     * @param  \Illuminate\Database\Eloquent\Builder  $query
     * @return \Illuminate\Database\Eloquent\Builder
     */
    protected function setKeysForSaveQuery(Builder $query)
    {
        $keys = $this->getKeyName();
        if(! is_array($keys)){
            return parent::setKeysForSaveQuery($query);
        }

        foreach($keys as $keyName){
            $query->where($keyName, '=', $this->getKeyForSaveQuery($keyName));
        }

        return $query;
    }

    /**
     * Get the primary key value for a save query.
     *
     * @param mixed $keyName
     * @return mixed
     */
    protected function getKeyForSaveQuery($keyName = null)
    {
        if(is_null($keyName)){
            $keyName = $this->getKeyName();
        }

        if (isset($this->original[$keyName])) {
            return $this->original[$keyName];
        }

        return $this->getAttribute($keyName);
    }

    /**
     * @deprecated - don't use find if has composite primary key
     */
    public static function find(){}

    /**
     * @deprecated - don't use whereKey if has composite primary key
     */
    public static function whereKey(){}

    /**
     * @deprecated - don't use whereKey if has composite primary key
     */
    public static function whereKeyNot(){}
}
